<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/11
 * Time: 13:34
 */

namespace common\data;

use common\ApiReturn;
use common\logic\Logic;
use common\LogicException;
use common\UnixTime;

class DataToolbar
{

    /**
     * @var DataView|null
     */
    private $view = null;

    /**
     * @var Logic|null
     */
    private $logic = null;

    /**
     * DataToolbar constructor.
     * @param DataView $dataView
     */
    public function __construct(DataView $dataView)
    {
        $this->view = $dataView;

        $logic = $dataView->getLogic();
        if (class_exists($logic)) {
            $this->logic = new $logic();
        }
    }

    /**
     * 响应数据
     * @return bool|mixed
     */
    public function response()
    {
        $method = strtolower(request()->method());
        $params = request()->param();
        if ($method === 'get') {
            $id = request()->param('id', 0);
            if ($id) {
                $method = 'get';
            } else {
                $method = 'lists';
            }
        }

        $result = false;
        if (method_exists($this, $method)) {
            $result = call_user_func_array([$this, $method], [$params]);
        }

        if ($result) {
            return ApiReturn::success($result);
        }

        return ApiReturn::data(LogicException::instance()->api());
    }

    /**
     * 设置搜索参数
     * @return array
     */
    protected function search()
    {
        $search_name = request()->param('search_name');
        $search_value = request()->param('search_value');

        if (empty($search_name)) {
            return [];
        }

        $query = $this->view->getQuery();

        $condition = [];
        foreach ($search_name as $key => $item) {
            $value = $search_value[$key] ?? null;
            if (null != $value) {
                $express = $query[$item] ?? '';

                if (empty($express) && $item == 'create_time') {
                    $express = 'date';
                }

                switch ($express) {
                    case 'like':
                        $condition[] = [$item, 'like', '%' . $value . '%'];
                        break;
                    case 'between':
                        $condition[] = [$item, 'between', json_decode($value, true)];
                        break;
                    case 'date':
                        $value = json_decode($value, true);
                        $start_time = UnixTime::instance()->startDay($value[0]);
                        $end_time = UnixTime::instance()->endDay($value[1]);
                        $condition[] = [$item, 'between', [$start_time, $end_time]];
                        break;
                    case 'datetime':
                        $value = json_decode($value, true);
                        $start_time = UnixTime::instance()->unix($value[0]);
                        $end_time = UnixTime::instance()->unix($value[1]);
                        $condition[] = [$item, 'between', [$start_time, $end_time]];
                        break;
                    default:
                        $condition[] = [$item, '=', $value];
                }
            }
        }

        return $condition;
    }

    /**
     * 根据主键获取单条数据
     * @param $search
     * @return array|\think\Model|null
     */
    protected function get($search)
    {
        return $this->logic->find($search);
    }

    /**
     * 获取数据列表
     * @param $params
     * @return array|\think\Collection|\think\Paginator
     */
    protected function lists($params)
    {
        $recycle = $params['recycle'] ?? 0;

        if ($recycle) {
            $this->logic->onlyTrashed = true;
        }

        $search = $this->search();

        return $this->logic->select($search);
    }

    /**
     * 保存数组
     * @param $params
     * @return bool|mixed
     */
    protected function post($params)
    {
        $validate = get_class($this->logic) . 'Validate';

        if (!class_exists($validate)) {
            $validate = '';
        }

        return $this->logic->setValidate($validate)->save($params);
    }

    /**
     * @param $params
     * @return bool|mixed
     */
    protected function put($params)
    {
        $validate = get_class($this->logic) . 'Validate';

        if (!class_exists($validate)) {
            $validate = '';
        }

        return $this->logic->setValidate($validate)->save($params, 'put');
    }

    /**
     * @param $params
     * @return bool|mixed
     */
    protected function patch($params)
    {
        $validate = get_class($this->logic) . 'Validate';

        if (!class_exists($validate)) {
            $validate = '';
        }

        if ($params['recovery'] ?? 0) {
            return $this->logic->setValidate($validate)->recovery($params['id']);
        } else {
            return $this->logic->setValidate($validate)->save($params, 'patch');
        }
    }

    /**
     * 删除
     * @param $params
     * @return mixed
     */
    protected function delete($params)
    {
        return $this->logic->delete($params['id'], $params['recycle']);
    }
}